package com.bigchun.woodhunter;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import bean.CodeBean;
import bean.ContentDataBean;
import myapp.MyApp;
import myview.CountDownButton;
import util.MyLog;
import util.RequestManager;
import util.SystemStatusManager;

public class RevisePhoneActivity extends BaseActivity {


    private LinearLayout ll_reback;
    private EditText et_phone_bycode;
    private EditText et_code_bycode;
    private CountDownButton tv_getcode;
    private Context context;
    private MyApp myapp;
    private TextView tv_sendMsg;
    private String token;
    private String mobile = "";
    private String apptype = "";
    private String textData;
    private SharedPreferences sharedPreferences;
    private TextView tv_bianma;
    private LinearLayout ll_bianma;
    private List<CodeBean.DataBean> temcodesList = new ArrayList<>();
    private ContentDataBean.DataBean textContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_revisephone);
        setTranslucentStatus();
        context = this;
        myapp = (MyApp) getApplicationContext();
        sharedPreferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        apptype = sharedPreferences.getString("apptype", "0");
        mobile = sharedPreferences.getString("mobile", "");
        textData = sharedPreferences.getString("textData", "");
        if ("0".equals(apptype)){
        }else if ("1".equals(apptype)){
            getCodeData();
        }
        initView();
        initLin();


    }


    private void initView() {

        ll_bianma = findViewById(R.id.ll_bianma);
        tv_bianma = findViewById(R.id.tv_bianma);

        ll_reback = findViewById(R.id.ll_reback);
        et_phone_bycode = findViewById(R.id.et_phone_bycode);
        et_code_bycode = findViewById(R.id.et_code_bycode);
        tv_getcode = findViewById(R.id.tv_getcode);
        tv_sendMsg = findViewById(R.id.tv_send_msg);
        et_phone_bycode.setText(mobile);
        et_phone_bycode.setSelection(mobile.length());
        TextView tv_title = findViewById(R.id.tv_title);
        TextView tv_input_new_phone = findViewById(R.id.tv_input_new_phone);
        textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {}.getType());
        if (textContent != null){
            tv_title.setText(textContent.getRevisephone());
            tv_input_new_phone.setText(textContent.getInput_new_phone());
            et_phone_bycode.setHint(textContent.getInput_phone());
            et_code_bycode.setHint(textContent.getInput_code());
            tv_getcode.setText(textContent.getGet_code());
            tv_sendMsg.setText(textContent.getDefine());
        }
        if ("0".equals(apptype)){
            ll_bianma.setVisibility(View.GONE);
        }else if ("1".equals(apptype)){
            ll_bianma.setVisibility(View.VISIBLE);
        }
    }


    private void initLin() {
        ll_reback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tv_getcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String phone = et_phone_bycode.getText().toString().trim();
                Log.e("手机号",phone+"   手机号");
                getPhoneAuthCode(phone);
            }
        });
        tv_sendMsg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                changePhone();
            }
        });
        ll_bianma.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //编码
                Intent intent = new Intent(context,BianmaActivity.class);
                startActivityForResult(intent,1);
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //此处可以根据两个Code进行判断，本页面和结果页面跳过来的值
        if (requestCode == 1 && resultCode == 3) {
            String result = data.getStringExtra("result");
            tv_bianma.setText("+"+result);
        }
    }
    /**
     * 发送验证码
     */
    private void getPhoneAuthCode(String phone) {
        String bianmacode = tv_bianma.getText().toString().trim();
        bianmacode = bianmacode.replace("+","");
        String url = myapp.getWebConfig() + "/api/sms/send";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("mobile", phone);
        paramsMap.put("event", "changemobile");
        paramsMap.put("is_material", apptype);
        paramsMap.put("country_code", bianmacode);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
//                {"code":1,"msg":"发送成功","time":"1571105679","data":8851}
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    msg.arg1 = 2;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });

    }
    /**
     * 修改手机号
     */
    private void changePhone() {
        String phone = et_phone_bycode.getText().toString().trim();
        String code = et_code_bycode.getText().toString().trim();
        Log.e("手机号",phone+"   手机号  "+code);
        String url = myapp.getWebConfig() + "/api/user/changemobile";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("mobile", phone);
        paramsMap.put("token", token);
        paramsMap.put("captcha", code);
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
//                {"code":1,"msg":"发送成功","time":"1571105679","data":8851}
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    msg.obj = jsonObject.getString("msg");
                    msg.arg1 = 3;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });

    }

    public Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            Intent intent = null;
            super.handleMessage(msg);
            switch (msg.arg1){
                case 0:
                    String str = (String) msg.obj;
                    Toast.makeText(context,str,Toast.LENGTH_LONG).show();
                    break;
                case 1:
                    Toast.makeText(context,textContent.getNet_error(),Toast.LENGTH_LONG).show();
                    break;
                case 2:
                    //这里判断是否倒计时结束，避免在倒计时时多次点击导致重复请求接口
                    tv_getcode.settime(120000);
                    if (tv_getcode.isFinish()) {
                        //发送验证码请求成功后调用
                        tv_getcode.start();
                    }
                    break;
                case 3:
                    String phone = et_phone_bycode.getText().toString().trim();
                    sharedPreferences.edit().putString("mobile", phone).commit();
                    String strstr = (String) msg.obj;
                    Toast.makeText(context,strstr,Toast.LENGTH_LONG).show();
                    finish();
                    break;
                case 4:

                    break;
                case 5:
                    if (temcodesList.size() > 0){
                        tv_bianma.setText("+"+temcodesList.get(0).getCode());
                    }
                    break;
                case 11:
                    if (!islogin){
                        islogin = true;
                        sharedPreferences.edit().putString("token", "").commit();
                        Intent intentl = new Intent(context, LoginActivity.class);
                        context.startActivity(intentl);
                        myapp.destoryActivity("主页面");
                    }
                    break;
            }
        }
    };
    private boolean islogin = false;

    /**
     * 设置状态栏背景状态
     */
    public  void setTranslucentStatus()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        {
            Window win =  getWindow();
            WindowManager.LayoutParams winParams = win.getAttributes();
            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            winParams.flags |= bits;
            win.setAttributes(winParams);
        }
        SystemStatusManager tintManager = new SystemStatusManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(0);//状态栏无背景
    }
    /**
     * 编码
     */
    private void getCodeData() {
        temcodesList.clear();

        String url = myapp.getWebConfig() + "/api/index/code";
        HashMap<String, String> paramsMap = new HashMap<>();
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONArray data = jsonObject.getJSONArray("data");
                    temcodesList = new Gson().fromJson(data.toString(), new TypeToken<List<CodeBean.DataBean>>() {
                    }.getType());


                    msg.arg1 = 5;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }else{
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }
}
